//
// service统一出口
import HYRequest from './request/request'
import { BASE_URL, TIME_OUT } from './request/config'
import { strage, Base64 } from '@/utils/index'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { refreshToken } from '@/api/user'

let isRefreshToken = false,
  patchList = []

const instance = axios.create({ baseURL: BASE_URL, timeout: TIME_OUT })
instance.interceptors.request.use((config: any) => {
  // 携带token的拦截
  const token = strage.getCache('lbs_tk')
  if (token) {
    config.headers.signature = token
  }
  return config
})

// token过期无感重新请求
function afreshRequest(config: object, resolve: any, reject: any) {
  instance
    .request<any>(config)
    .then(res => {
      resolve(res)
    })
    .catch(err => {
      resolve(err)
      // 将showLoading设置true, 这样不会影响下一个请求
    })
}
//请求实例
const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config: any) => {
      // 携带token的拦截
      const token = strage.getCache('lbs_tk')
      if (token) {
        config.headers.signature = token
      }
      //等待刷新token
      if (isRefreshToken && config.url !== 'sso/keepSignature') {
        return new Promise((resolve, reject) => {
          const timer: number = window.setInterval(() => {
            if (isRefreshToken) {
              return
            } else {
              window.clearInterval(timer)
            }
            resolve(config)
          }, 200)
        })
      } else {
        return config
      }
    },
    requestInterceptorCatch: err => {
      return err
    },
    responseInterceptor: res => {
      const { config, data } = res
      console.log(data)
      // 获取token
      if ((config.url === 'sso/login' || config.url === 'sso/keepSignature') && data) {
        const {
          data: { accessKey, uuid, expireTime },
        } = data
        const signature = `${accessKey}|${expireTime}|${uuid}`
        const token = Base64.encode(signature).replace(/=/g, '')
        strage.setCache('lbs_tk', token)
        return data
      } else if (res.data.state === 50011) {
        // 签名过期处理
        isRefreshToken = true
        patchList = []
        return new Promise((resolve, reject) => {
          refreshToken()
            .then(result => {
              isRefreshToken = false
              afreshRequest(res.config, resolve, reject)
            })
            .catch(err => {
              reject(err)
            })
        })
      } else if (data.state === 1) {
        return data
      } else {
        ElMessage({
          showClose: true,
          message: data.result,
          type: 'error',
        })
        return res
      }
    },
    responseInterceptorCatch: err => {
      return err
    },
  },
})

export default hyRequest
